import os
from flask import Flask, render_template, redirect, session, g, request, jsonify, url_for, flash
from werkzeug.utils import secure_filename
import config
from decorators import login_required, login_req
from exts import db,mail
from flask_migrate import Migrate
import cryptography
from blueprints.products import bp as goods_bp
from blueprints.sale import bp as sale_bp
from blueprints.purchase_orders import bp as procurement_bp
from blueprints.member import bp as member_bp
from models import UserModel


app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
app.register_blueprint(goods_bp)
app.register_blueprint(procurement_bp)
app.register_blueprint(member_bp)
app.register_blueprint(sale_bp)
migrate=Migrate(app,db)

@app.before_request
def my_before_request():
    user_id=session.get("user_id")
    if user_id:
        user=UserModel.query.get(user_id)
        setattr(g,"user",user)
    else:
        setattr(g,"user",None)
# 调用主页
@app.route('/')
@login_required
def hello_world():
    return redirect(url_for("products.products"))



@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("登录.html")
    else:
        username = request.form.get('username')
        password = request.form.get('password')

        # 根据数据库模型来查询用户表
        user = UserModel.query.filter_by(username=username).first()

        if user and user.password == password:
            # 登录成功，可以进行一些操作，比如设置 session
            session['user_id'] = user.uid
            return redirect(url_for("products.products"))
        else:
            # 登录失败，返回错误信息
            error_message = "用户名或密码错误"
            return redirect(url_for("login"))





if __name__ == '__main__':
    app.run(debug=True)
